<template>
  <div>
    <treeselect
      :ref="selectTreeRef"
      v-model.lazy="childModel"
      name="treeselect"
      :multiple="configDefault.multiple"
      :clearable="configDefault.clearable"
      :searchable="configDefault.searchable"
      :open-on-click="configDefault.openOnClick"
      :open-on-focus="configDefault.openOnFocus"
      :clear-on-select="configDefault.clearOnSelect"
      :close-on-select="configDefault.closeOnSelect"
      :append-to-body="configDefault.appendToBody"
      :limit="configDefault.limit"
      :show-count="configDefault.showCount"
      :always-open="configDefault.alwaysOpen"
      :defaultExpandLevel="configDefault.defaultExpandLevel"
      :disabled="disabled"
      :normalizer="normalizer"
      :placeholder="disabled ? '' : configDefault.placeholderLabel"
      :max-height="maxTreeHeight"
      :options="configDefault.options"
      @open="selectTreeOpen"
      @close="selectTreeClose"
      @select="selectTreeSelect"
      @input="selectTreeChange"
      @deselect="selectTreeDeselect"
      @search-change="selectTreeSearchChange"
    />
  </div>
</template>

<script>
import treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getComboTreeData } from "@/components/api/fromSource.js";
import XEUtils from "xe-utils";
let configProps = {};
export default {
  components: {
    treeselect,
  },
  props: {
    //自定义ref
    selectTreeRef: {
      type: String,
      default() {
        return "vueSelectTree";
      },
    },
    model: {
      // 当前组件绑定值
      type: [String, Number, Boolean, Array],
      require: true,
    },
    modelKey: {
      //当前绑定值key，可以用于formData中获取到当前组件渲染配置items
      type: String,
      default() {
        return "";
      },
    },
    fromSource: {
      //用于formData中获取到当前组件渲染配置items
      type: [Array, String],
      default() {
        return "";
      },
    },
    which: {
      //第几组下拉树
      type: [String, Number],
      default() {
        return 1;
      },
    },
    disabled: {
      // 当前组件是否禁用
      type: Boolean,
      default() {
        return false;
      },
    },
    config: {
      //私有配置数据
      type: [String, Object],
      require: true,
    },
    formConfigData: {
      //配置数据
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      childModel: null,
      maxTreeHeight: 400,
      configDefault: {
        options: [],
        alwaysOpen: false, //恒显示
        clearable: true, //清空按钮
        searchable: true, //搜索框
        openOnClick: true, //单击控件时是否自动打开菜单。
        openOnFocus: false, //控件聚焦时是否自动打开菜单
        clearOnSelect: true,
        closeOnSelect: true,
        appendToBody: false, // 节点插入到body上
        showCount: true, //子节点的总数
        limit: 1, //复选框时显示几个节点，其他的 +1
        props: {
          // 当前id下拉选项配置 {label:'显示文本值',dataId:'当前选项绑定值'}
          label: "label",
          id: "id",
          children: "children",
        },
        filter: "", //过滤条件 filter:"mof_div_code like '12%'"
        placeholderLabel: "",
        defaultExpandLevel: 5,
        isCustomData: true,
        multiple: false,
      },
      normalizer(node) {
        //自定义键名
        if (
          (node.children && node.children.length === 0) ||
          node.children == null
        ) {
          delete node.children;
        }
        return {
          id: node[configProps.id],
          label: node[configProps.label],
          children: node[configProps.children],
        };
      },
    };
  },
  watch: {
    childModel(val, oldVal) {
      if (
        (this.configDefault.multiple && !XEUtils.isEqual(val, oldVal)) ||
        (!this.configDefault.multiple && val !== oldVal)
      ) {
        this.$emit("update:model", val);
      }
    },
    model(val, oldVal) {
      if (
        ((this.configDefault.multiple &&
          !XEUtils.isEqual(val, this.childModel)) ||
          (!this.configDefault.multiple && val !== this.childModel)) &&
        val
      ) {
        this.childModel = val;
      }
    },
    formConfigData: {
      handler(newVal) {
        let formConfigObj = newVal
          ? newVal[this.fromSource] || newVal[this.modelKey]
          : {};
        let publicConfigObj = newVal ? newVal["publicAttr"] : {};
        let cfg =
          this.config && XEUtils.isString(this.config)
            ? XEUtils.toStringJSON(this.config)
            : this.config || {};
        this.configDefault = XEUtils.merge(
          this.configDefault,
          publicConfigObj,
          cfg,
          formConfigObj
        );
        configProps = this.configDefault.props;
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  created() {},
  mounted() {
    //多选时可能存在多个键值
    if (this.configDefault.multiple) {
      this.childModel = this.model && this.model.length > 0 ? this.model : [];
    } else {
      this.childModel = this.model || this.model == 0 ? this.model : null;
    }
  },
  methods: {
    selectTreeOpen() {
    //触发选择框事件
      if (!this.configDefault.isCustomData) {
        let params = {
          // elementCode: this.fromSource || this.modelKey,
          // filter: this.configDefault.filter
        };
        getComboTreeData(params).then((res) => {
          this.initSelectTreeData(res.data);
        });
      }
      this.$emit("selectTreeOpenCallback");
    },
    initSelectTreeData(data) {
      this.configDefault.options = data && data.length > 0 ? data : [];
    },
    //给默认选择框内赋值
    setSelectValues() {},
    selectTreeClose(newVal, instanceId) {
    //selecttree下拉框关闭的时触发的事件
      this.$emit("closeCallback", this.modelKey + "_" + this.which, newVal);
    },
    //             离开搜索的文本框事件
    selectTreeChange(newVal, instanceId) {
      let currentObj = [];
      let idVal = this.configDefault.props.id;
      XEUtils.eachTree(
        this.configDefault.options,
        (val) => {
          if (this.configDefault.multiple) {
            if (newVal && newVal.includes(val[idVal])) {
              currentObj.push(val);
            }
          } else if (val[idVal] === newVal) {
            currentObj = val;
            return;
          }
        },
        { children: this.configDefault.props.children }
      );
      this.$emit(
        "changeCallback",
        this.modelKey + "_" + this.which,
        newVal,
        currentObj
      );
    },
    //             选中节点触发事件
    selectTreeSelect(node, instanceId) {
      this.$emit("selectCallback", this.modelKey + "_" + this.which, node);
    },
    //             取消节点事件
    selectTreeDeselect(node, instanceId) {
      //   console.log("selectTreeDeselect", node, instanceId);
    },
    selectTreeSearchChange(searchQuery, instanceId) {
      //   console.log("selectTreeSearchChange", searchQuery, instanceId);
    },
  },
};
</script>

<style lang="less"></style>
